package com.spddr.pmos.rpt.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Period;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.spddr.pmos.domain.Metrics;
import com.spddr.pmos.rpt.RptReservoirFlow;
import com.spddr.pmos.rpt.RptReservoirSupplyLevel;
import com.spddr.pmos.rpt.pojo.CellValue;

import cn.seqdata.echarts.Legend;
import cn.seqdata.echarts.Option;
import cn.seqdata.echarts.axis.CategoryAxis;
import cn.seqdata.echarts.axis.ValueAxis;
import cn.seqdata.echarts.data.Data;
import cn.seqdata.echarts.series.Line;
import cn.seqdata.echarts.series.MarkLine;
import cn.seqdata.tags.Point;
import cn.seqdata.tags.common.IdTags;

@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RptReservoirFlowImpl extends AbstractPivotChartImpl implements RptReservoirFlow {

	private List<Metrics> metrics = Lists.newArrayList(Metrics.FLOW_IN, Metrics.FLOW_OUT, Metrics.FLOW_OUT_USEFUL,
			Metrics.FLOW_OUT_USELESS);

	protected Period intervalOfStorage() {
		return Days.ONE.equals(interval) ? Hours.ONE.toPeriod() : Days.ONE.toPeriod();
	}

	@Override
	public List<CellValue> loadPivot() {
		return metrics.stream().flatMap(x -> {
			return sim(1).getValue().getValues().stream()
					.map(v -> new CellValue(new Point<>(x.name, new IdTags(id)), v, x.desc, null));
		}).collect(Collectors.toList());
	}

	@Override
	public Option chart() {
		Option option = new Option();

		CategoryAxis xAxis = new CategoryAxis().show(true);
		if (Hours.ONE.toPeriod().equals(intervalOfStorage())) {
			xAxis.setFunc(String.format("Admin.Array.hours(1, 'H:i', '%s', '%s')", getStartTime(), getEndTime()));
		} else {
			xAxis.setFunc(String.format("Admin.Array.dates(1, 'm-d', '%s', '%s')", getStartTime(), getEndTime()));
		}
		option.xAxis(xAxis);

		option.yAxis(new ValueAxis().show(true));

		option.legend().show(true);
		metrics.stream().forEach(x -> {
			option.legend().data().add(x.desc);

			Line line = new Line(x.desc);
			sim(1).getValue().getValues().forEach(v -> {
				line.data().add(String.format("%.2f", v.getValue()));
			});
			option.series().add(line);
		});

		return option;
	}

}
